package com.tanhua.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.itheima.tanhua.dto.AdminDto;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhua.vo.AdminVo;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取验证码
     */
    @GetMapping("/verification")
    public void sendVerification(@RequestParam("uuid") String uuid, HttpServletResponse response) throws IOException {
        //使用hutool提供的验证码工具
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(299, 97);
        //获取验证码
        String code = circleCaptcha.getCode();
        //存到redis中 三分钟有效
        redisTemplate.opsForValue().set(Constants.ADMIN_CODE + uuid, code, Duration.ofMinutes(3));
        //返回图片到前端
        circleCaptcha.write(response.getOutputStream());
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody AdminDto adminDto) {
        //调用service完成登录。
        Map token = adminService.login(adminDto);
        return ResponseEntity.ok(token);
    }

    /**
     * 获取用户详情资料
     */
    @PostMapping("/profile")
    public ResponseEntity profile() {
        //获取用户id
        Long userId = AdminHolder.getUserId();
        AdminVo adminVo = adminService.findAdminById(userId);
        return ResponseEntity.ok(adminVo);
    }

    /**
     * 登出
     */
    @PostMapping("/logout")
    public ResponseEntity logout() {
        return ResponseEntity.ok(null);
    }

}
